package awk.jdk8;

import static java.util.stream.Collectors.toList;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * https://blog.csdn.net/sunjin9418/article/details/53086565
 * created with IDEA
 *
 * @author haifeng.wang
 * @since 2019-04-17-14:24
 */
public class Jdk8StreamTest {

    public void test01() {
        //过滤
        List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
        numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);

        //截断流
        List<Dish> menu = new ArrayList<>();
        List<Dish> dishes = menu.stream().filter(d -> d.getCalories() > 300).limit(3).collect(toList());

        //跳过元素
        dishes = menu.stream().filter(d -> d.getCalories() > 300).skip(2).collect(toList());
        //映射
        List<String> dishNames = menu.stream().map(Dish::getName).collect(toList());

        List<String> words = Arrays.asList("Java8", "Lambdas", "In", "Action");
        List<Integer> wordLengths = words.stream().map(String::length).collect(toList());

        // 展开流  hello world 列出所有单个字母，不要重复
        List<String> uniqueCharacters = words.stream().map(w -> w.split("")).flatMap(Arrays::stream).distinct()
            .collect(Collectors.toList());

        //任意匹配
        if (menu.stream().anyMatch(Dish::isVegetarian)) {
            System.out.println("The menu is (somewhat) vegetarian friendly!!");
        }
        //全部匹配
        boolean isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000);
        //全部不匹配
        isHealthy = menu.stream().noneMatch(d -> d.getCalories() >= 1000);
        //获取任意一个元素
        Optional<Dish> dish = menu.stream().filter(Dish::isVegetarian).findAny();

        //归约:将一个流中的元素反复结合运算得到一个值。
        //使用流的API求和
        int sum2 = numbers.stream().reduce(0, (a, b) -> a + b);

        //求最大值
        Optional<Integer> max = numbers.stream().reduce(Integer::max);

        //求最小值
        Optional<Integer> min = numbers.stream().reduce(Integer::min);

    }

    class Dish {

        private int calories;
        private String name;
        private boolean vegetarian;

        public boolean isVegetarian() {
            return vegetarian;
        }

        public void setVegetarian(boolean vegetarian) {
            this.vegetarian = vegetarian;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getCalories() {
            return calories;
        }

        public void setCalories(int calories) {
            this.calories = calories;
        }

    }
}
